package cn.kfu.service.impl;

import cn.kfu.dao.UserDao;
import cn.kfu.model.User;
import cn.kfu.service.UserService;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Override
    public List<User> findAll() {
        List<User> users = new ArrayList<>();
        userDao.findAll().forEach(users::add);
        return users;
    }

    @Transactional
    @Override
    public boolean login(User user) {
//        userDao.save(user);
        return true;
    }

    @Override
    public boolean register(User user) {
        String salt = RandomStringUtils.randomNumeric(6, 8);
        user.setSalt(salt);
        Md5Hash md5Hash = new Md5Hash(user.getPassword(), salt);
        user.setState(1);
        user.setPassword(md5Hash.toString());
        user.setCreateTime(new Date());
        userDao.save(user);
        return true;
    }

    @Override
    public User findUserByUsername(String username) {
        List<User> users = null;
        if (username.contains("@")) {
            users = userDao.findByEmail(username);
        } else {
            users = userDao.findByCellphone(username);
        }
        if (users != null && users.size() > 0) {
            return users.get(0);
        }
        return null;
    }
}
